package com.chenxin.quartz.process.mesTask.impl;

import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.domain.mesResponse.MesTokenResponseDTO;
import com.chenxin.interact.handler.mesHandler.MesTokenHandler;
import com.chenxin.interact.service.IUrlMapService;
import com.chenxin.quartz.process.mesTask.ITokenRequestProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TokenRequestProcess implements ITokenRequestProcess {
    @Autowired
    private IUrlMapService urlMapService;
    @Autowired
    private MesTokenHandler mesTokenHandler;

    @Override
    public ProcResult call(String method) {
        // 0.判断对用的URL是否在[wms_url_map]表中进行配置
        UrlMap tokenUrl = urlMapService.selectUrlMapByUrlNo("MES_POST_URL");
        if (tokenUrl == null) {
            return ProcResult.error("token_req_err#001", "【MES_COMM_URL】未在表【wms_url_map】中进行配置!请核查");
        }
        try {
            MesTokenResponseDTO tokenResponse = mesTokenHandler.requestToken(tokenUrl, method);
            // 直接获取令牌
            String token = tokenResponse.getContext().getTicket();
            tokenUrl.setToken(token);
            // 将令牌信息写入数据库
            urlMapService.updateUrlMap(tokenUrl);
        } catch (Exception e) {
            throw new WmsException("token_req_err#002", "获取MES令牌异常，causeBy:" + e.getMessage());
        }
        return null;
    }
}
